"use client";
import {
    getCommissionApi,
    getRegisterCountApi,
    getTotalCountApi,
    getWithdrawalApi,
    UserAgentToDayInfo,
    UserCommissionStatistics,
} from "@/api/summary";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { useRequest } from "ahooks";
import { Toast } from "antd-mobile";
import { useLocale, useTranslations } from "next-intl";

import { getToken } from "@/utils/Cookies";
import { copyText } from "@/utils/methods";
import { FC, useRef, useState } from "react";
import "./page.scss";

interface Props {}

const App: FC<Props> = (props) => {
    const t = useTranslations("SummaryPage");
    const locale = useLocale();

    const sliderRef = useRef<HTMLDivElement>(null);
    const [num, setNum] = useState(100);
    const [money, setMoney] = useState("5000");
    const { userInfo } = useUserInfoStore();
    const token = getToken();

    // 生成分享链接
    const BASE_URL = process.env.NEXT_PUBLIC_SHARE_URL;
    const shareUrl = `${BASE_URL}/${locale}/${userInfo ? userInfo.referrer_code : "xxxxxx"}`;
    // 轮询时间
    const TIME = 180000;
    const [todayData, setTodayData] = useState<UserAgentToDayInfo>({
        commissar: 0,
        effective_amount: 0,
        recharge_user_count: 0,
        reg_count: 0,
    });
    const getUserMoneyHandler = () => {
        if (token) {
            return getRegisterCountApi();
        }
        return Promise.reject();
    };

    useRequest(getUserMoneyHandler, {
        pollingInterval: TIME,
        pollingWhenHidden: true,
        pollingErrorRetryCount: 3,
        staleTime: 5000,
        refreshDeps: [token],
        onError: (error) => {},
        onSuccess: (res) => {
            if (res.data) {
                setTodayData(res.data);
            }
        },
    });

    const [totalData, setTotalData] = useState<UserAgentToDayInfo>({
        commissar: 0,
        effective_amount: 0,
        recharge_user_count: 0,
        reg_count: 0,
    });
    const getTotalCount = () => {
        if (token) {
            return getTotalCountApi();
        }
        return Promise.reject();
    };

    useRequest(getTotalCount, {
        pollingInterval: TIME,
        pollingWhenHidden: true,
        pollingErrorRetryCount: 3,
        staleTime: 5000,
        refreshDeps: [token],
        onError: (error) => {},
        onSuccess: (res) => {
            if (res.data) {
                setTotalData(res.data);
            }
        },
    });

    const [commissionData, setCommissionData] = useState<UserCommissionStatistics>({
        commissar: 0,
        level: 0,
        withdrawal_commissions: 0,
    });
    const getCommission = () => {
        if (token) {
            return getCommissionApi();
        }
        return Promise.reject();
    };

    const { run: commissionRun } = useRequest(getCommission, {
        pollingInterval: TIME,
        pollingWhenHidden: true,
        pollingErrorRetryCount: 3,
        staleTime: 5000,
        refreshDeps: [token],
        onError: (error) => {},
        onSuccess: (res) => {
            if (res.data) {
                setCommissionData(res.data);
            }
        },
    });

    const handleSlide: any = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
        if (sliderRef.current) {
            const startX = sliderRef.current.getBoundingClientRect().x;
            const x = e.clientX - startX;
            const xRem = x / (144 * 0.6);
            const intNum = Math.round(10000 * xRem) - Math.round((10000 * xRem) % 10);
            setNum(intNum);
            const m = intNum * 50;
            let r = "";
            const arr = m.toString().split("");
            arr.forEach((item, i) => {
                if (i !== arr.length - 1 && (arr.length - i - 1) % 3 === 0) {
                    r += item + ",";
                } else {
                    r += item;
                }
            });

            setMoney(r);
            const scale = (Math.round(xRem * 10000) / 100.0).toFixed(2) + "%";
            sliderRef.current.style.width = scale;
        }
    };

    const copy = (text: string) => {
        copyText(text);
        Toast.show({ icon: "success", content: t("copySuc"), maskClickable: false });
    };

    const withdrawalHandler = async () => {
        await getWithdrawalApi({ amount: 10 });
        // 间隔时间
        setTimeout(() => {
            commissionRun();
        }, 100);
    };

    // @ts-ignore
    return (
        <div className="content">
            <div className="summary referral-router-view">
                <div className="content" style={{ marginTop: 0 }}>
                    <div className="title">
                        <div>
                            {t("Hoje")}
                            <span className="iconfont icon-bangzhu" />
                        </div>
                    </div>
                    <div className="cardMian">
                        <ul className="statistics-card">
                            <li>
                                <p className="num">{todayData.reg_count}</p>
                                <p> {t("Inscrições")} </p>
                            </li>
                            <li>
                                <p className="num">{todayData.recharge_user_count}</p>
                                <p> {t("Novos")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {todayData.effective_amount}
                                </p>
                                <p> {t("Aposta")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {todayData.commissar}
                                </p>
                                <p> {t("Comissão")} </p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div>
                            {t("Total")}
                            <span className="iconfont icon-bangzhu" />
                        </div>
                    </div>
                    <div className="cardMian">
                        <ul className="statistics-card">
                            <li>
                                <p className="num">{totalData.reg_count}</p>
                                <p> {t("Inscrições")} </p>
                            </li>
                            <li>
                                <p className="num">{totalData.recharge_user_count}</p>
                                <p> {t("Jogadores")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {totalData.effective_amount}
                                </p>
                                <p> {t("ApostaTotal")} </p>
                            </li>
                            <li>
                                <p className="num">
                                    <span className={"mr-[5px]"}>{t("R$")}</span>
                                    {totalData.commissar}
                                </p>
                                <p>RS {t("Comissão")} </p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div>
                            {t("Comissão")}
                            <span className="iconfont icon-bangzhu" />
                        </div>
                    </div>
                    <div className="cardMian">
                        <div className="vip">
                            <div className="level">
                                <span className="iconfont icon-vip"></span>
                                <span className="levelNum">{commissionData.level}</span>
                            </div>
                            <div>
                                {t("Nível")}
                                <span className="iconfont icon-tishi"></span>
                            </div>
                        </div>
                        <div>
                            <ul className="commission">
                                <li>
                                    <p className="num">
                                        <span>{t("R$")}</span>
                                        <span className="cash">
                                            {commissionData.withdrawal_commissions}
                                        </span>
                                    </p>
                                    <p> {t("TotalPago")} </p>
                                </li>
                                <li>
                                    <p className="num">
                                        <span>{t("R$")}</span>
                                        <span className="cash">{commissionData.commissar}</span>
                                    </p>
                                    <p> {t("Não")} </p>
                                </li>
                            </ul>
                            <div className="wallet">
                                <div className="btn" onClick={withdrawalHandler}>
                                    {t("TRANSFERIR")}{" "}
                                </div>
                                <div className="tip">
                                    <span className="iconfont icon-tishi1"></span>
                                    {t("Valor")}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="content shareMain">
                    <div className="title">
                        <div>{t("title1")}</div>
                    </div>
                    <div className="share">
                        <ul className="sharePlatform">
                            <li>
                                <a href="">
                                    <img src="/img/facebook.webp" alt="" />
                                </a>
                                <span>{t("Facebook")}</span>
                            </li>
                            <li>
                                <a href="">
                                    <img src="/img/WhatsApp.webp" alt="" />
                                </a>
                                <span>{t("WhatsApp")}</span>
                            </li>
                            <li>
                                <a href="">
                                    <img src="/img/Telegram.png" alt="" />
                                </a>
                                <span>{t("Telegram")}</span>
                            </li>
                            <li>
                                <a href="">
                                    <img src="/img/Twitter.webp" alt="" />
                                </a>
                                <span>{t("Twitter")}</span>
                            </li>
                            <li>
                                <a href="">
                                    <img src="/img/email.webp" alt="" />
                                </a>
                                <span>{t("Email")}</span>
                            </li>
                        </ul>
                    </div>
                    <div className="shareLink">
                        <div className="">{t("content1")}</div>
                        <div className="copyUrl">
                            <span className="url omitWrap">{shareUrl}</span>
                            <span id="copy" onClick={() => copy(shareUrl)}>
                                {t("Cópia")}
                            </span>
                        </div>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div> {t("title2")}</div>
                    </div>
                    <div>
                        <div className="tel-box">
                            <a href="" className="telicon">
                                <img src="/img/telegram.webp" alt="" />
                            </a>
                            <div className="hintTitle3">{t("content2-1")}</div>
                        </div>
                        <div className="hintTitle2">
                            <i className="iconfont icon-tishi"></i>
                            {t("content2-2")}
                            <a
                                href=""
                                style={{
                                    borderBottom: "1px solid rgb(109, 155, 195)",
                                    color: "#0000EE",
                                }}
                            >
                                {t("business")}
                            </a>
                        </div>
                    </div>
                </div>
                <div className="content">
                    <div className="title">
                        <div>
                            {t("title3")}
                            <span className="iconfont icon-bangzhu"></span>
                        </div>
                    </div>
                    <div className="hint">
                        <div className="hintTitle">{t("content3")}</div>
                        <div className="imgContent">
                            <img src="/img/cash.png" alt="" />
                            <div>
                                {t("number")}
                                {num}
                                <br />
                                {t("Comissão")} &gt; {t("R$")} {money} {t("money")}
                            </div>
                            <div
                                className="slider van-slider"
                                style={{ height: "0.02rem" }}
                                onClick={handleSlide}
                            >
                                <div
                                    className="van-slider__bar"
                                    style={{ width: "0.900901%", background: "rgb(0, 157, 128)" }}
                                    ref={sliderRef}
                                >
                                    <div role="slider" className="van-slider__button-wrapper">
                                        <div className="img"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="relationSchema">
                            <div className="groupTitle">{t("title4")}</div>
                            <img src="/img/group_br.webp" alt="" className="groupImg" />
                            <ul className="rules">
                                <li>
                                    {t("content4-1")}
                                    <span style={{ color: "red" }}>{t("red")}</span>.
                                </li>
                                <li>{t("content4-2")}</li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div className="content"></div>
            </div>
        </div>
    );
};

export default App;
